package com.easybuilder.core.im.netty;

import com.sun.corba.se.internal.CosNaming.BootstrapServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class IMServer {

    public static void main(String[] args) {

        // boosGroup线程组，负责处理连接操作
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        // workGroup线程组，负责业务操作
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        // 辅助启动类
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // 设置两个线程组
        serverBootstrap.group(bossGroup, workGroup)
                // 采用nio通道
                .channel(NioServerSocketChannel.class)
                // 设置处理连接的线程数量
                .option(ChannelOption.SO_BACKLOG, 128)
                // 设置连接后保持存活状态
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                // 设置处理器
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 通过管道对象，向其中添加处理器
                        // 管道是双向的，其中维护了一系列处理器链，读取时，从前往后执行处理器链，写操作时，从后向前执行处理器链
                        socketChannel.pipeline().addLast(new IMServerReadHandler());
                    }
                });
        try {
            // 绑定ip和端口，并同步
            ChannelFuture ch = serverBootstrap.bind("localhost", 6666).sync();
            System.out.println("netty server started >>>>>>>>>>>>>");
            // 监听通道关闭
            ch.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            System.out.println("netty server start failure!");
            e.printStackTrace();
        } finally {
            bossGroup.shutdown();
            workGroup.shutdown();
        }
    }
}
